<template>
  <Popup v-model="show" position="bottom">
    <DatetimePicker
      v-model="currentDate"
      :type="type"
      :minDate="minDate"
      :maxDate="maxDate"
      @confirm="onConfirmClick"
      @cancel="onCancelClick"
    />
  </Popup>
</template>

<script>
import Popup from '@/widgets/Popup'
import DatetimePicker from '@/widgets/DatetimePicker'

export default {
  name: 'PopupDateTimeCpt',
  components: {
    Popup,
    DatetimePicker
  },
  props: {
    type: {
      type: [String],
      default: 'date',
      validator: function (value) {
        return (
          [
            'date',
            'time',
            'datetime',
            'year-month',
            'month-day',
            'datehour'
          ].indexOf(value) !== -1
        )
      }
    }
  },
  data() {
    return {
      show: false,
      currentDate: new Date()
    }
  },
  computed: {
    minDate() {
      const today = new Date()
      return new Date(today.getFullYear() - 100, 1, 1)
    },
    maxDate() {
      const today = new Date()
      return new Date(
        today.getFullYear() + 100,
        today.getMonth() + 1,
        today.getDate()
      )
    }
  },
  methods: {
    showView() {
      this.show = true
    },
    onConfirmClick(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      if (second >= 0 && second <= 9) {
        second = `0${second}`
      }
      if (this.type === 'datetime') {
        this.timeValue = `${year}-${month}-${day} ${hour}:${minute}:00`
      } else {
        this.timeValue = `${year}-${month}-${day}`
      }
      this.$emit('onSelectedChange', this.timeValue)
      this.show = false
    },
    onCancelClick() {
      this.show = false
    }
  }
}
</script>
